#include "mainwindow.h"
#include <QApplication>
#include <QDir>
#include <QMessageBox>
#include <QPluginLoader>
#include <QPushButton>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    myPlugin = nullptr;

    QPushButton *button = new QPushButton("Button", this);
    button->setGeometry(62, 40, 75, 30);

    connect(button, SIGNAL(clicked(bool)), this, SLOT(loadPlugin()));
}

MainWindow::~MainWindow()
{
}

bool MainWindow::loadPlugin()
{
    if (myPlugin != nullptr)
    {
        return true;
    }

    QDir pluginsDir(qApp->applicationDirPath());

    //在exe目录下新建了plugins文件夹，把生成的dll文件放到此文件夹下
    pluginsDir.cd("plugins");

    // 加载当前文件夹下的dll文件
    foreach (QString fileName, pluginsDir.entryList(QDir::Files))
    {
        QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName));
        QObject *instance = pluginLoader.instance();
        if (instance != nullptr)
        {
            myPlugin = qobject_cast<MyInterface *>(instance);
            if (myPlugin != nullptr)
            {
                QMessageBox::information(this, "load plugin ok", QString::number(myPlugin->add(7, 8)));
                return true; // 这里只加载一个plugin
            }
        }
        else
        {
            QMessageBox::critical(this, "load plugin failed", pluginLoader.errorString());
            return false;
        }
    }

    return false;
}
